package com.zrfintech.common;

import com.google.common.collect.Maps;
import com.zrfintech.constant.RequestContextField;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 请求上下文
 * 
 * @author tangyuanliang
 *
 */
public class RequestContext {
    private static Logger LOGGER = LoggerFactory.getLogger(RequestContext.class);

    private static ThreadLocal<Map<String, Object>> local = new ThreadLocal<Map<String, Object>>();

    public static void set(Map<String, Object> map) {
        local.set(map);
    }

    public static Map<String, Object> get() {
        Map<String, Object> map = local.get();
        return map;
    }

    public static Object get(String key) {
        Map<String, Object> requestContext = local.get();
        if (requestContext != null) {
            return requestContext.get(key);
        }
        return null;
    }


    /**
     * 移除当前线程变量
     */
    public static void remove() {
        local.remove();
    }

    /**
     * 清空当前线程变量
     */
    public static void clear() {
        Map<String, Object> requestContext = local.get();
        if (requestContext != null) {
            requestContext.clear();
        }
        local.remove();
    }

    /**
     * set 一级上下文
     */
    public static void setFirstContext(String key, Object value) {
        Map<String, Object> requestContext = local.get();
        if (requestContext != null) {
            requestContext.put(key, value);
        }
    }

    /**
     * set 二级上下文，一级默认为 key = requestContext
     */
    public static void setSecondContext(String key, Object value) {
        if (key != null && value != null && !Thread.currentThread().isInterrupted()) {
            setSecond(RequestContextField.REQCTX_FIELD_REQCTX, key, value);
        }
    }


    @SuppressWarnings("unchecked")
    private static void setSecond(String firstKey, String key, Object value) {
        Map<String, Object> requestContext = local.get();
        if (MapUtils.isNotEmpty(requestContext)) {
            if (!requestContext.containsKey(firstKey)) {
                requestContext.put(firstKey, Maps.newConcurrentMap());
            }
            Map<String, Object> reqContext = (Map<String, Object>) requestContext.get(firstKey);
            reqContext.put(key, value);
        }
    }

    @SuppressWarnings("unchecked")
    public static Object getSecond(String key) {
        Map<String, Object> requestContext = local.get();
        if (MapUtils.isNotEmpty(requestContext)
                && requestContext.containsKey(RequestContextField.REQCTX_FIELD_REQCTX)) {
            Map<String, Object> reqContext = (Map<String, Object>) requestContext
                    .get(RequestContextField.REQCTX_FIELD_REQCTX);
            return reqContext.get(key);
        }
        return null;
    }
//
//    /**
//     * set 数据源计费信息上下文，一级默认为 key = requestContext，二级默认为 key = ds_charge_detail
//     */
//    @SuppressWarnings("unchecked")
//    public static void setChargeContext(String key, Object value) {
//        Map<String, Object> requestContext = local.get();
//        if (MapUtils.isNotEmpty(requestContext)
//                && requestContext.containsKey(RequestContextField.REQCTX_FIELD_REQCTX)) {
//            Map<String, Object> reqContext = (Map<String, Object>) requestContext
//                    .get(RequestContextField.REQCTX_FIELD_REQCTX);
//            JSONObject chargeDetail = (JSONObject) reqContext.get(InstRequestContext.INST_DSCHARGE_DETAIL);
//            if (null == chargeDetail) {
//                chargeDetail = new JSONObject();
//                chargeDetail.put(key, value);
//                reqContext.put(InstRequestContext.INST_DSCHARGE_DETAIL, chargeDetail);
//            } else {
//                chargeDetail.put(key, value);
//            }
//        }
//    }
//
//    /**
//     * 上下文存储，数据源计费信息
//     */
//    public static void setChargeContext(DSChargeEnum chargeEnum, Object... values) {
//        try {
//            if (chargeEnum != null && CollectionUtils.isNotEmpty(chargeEnum.getChargeKes()) && values != null
//                    && !Thread.currentThread().isInterrupted()) {
//                JSONObject dsDetail = new JSONObject();
//                for (int i = 0; i < chargeEnum.getChargeKes().size(); i++) {
//                    dsDetail.put(chargeEnum.getChargeKes().get(i), values[i]);
//                }
//                setChargeContext(chargeEnum.getCode(), dsDetail);
//            }
//            LOGGER.info("[setChargeContext]success chargeEnum={}, values={}.", JSON.toJSONString(chargeEnum),
//                    JSON.toJSONString(values));
//        } catch (Exception e) {
//            LOGGER.error("[setChargeContext]exception.", e);
//        }
//    }
//
//
//    /**
//     * 获取请求的reqId
//     * @return
//     */
//    public static String getReqId(){
//        String reqId = "";
//        Map<String, Object> requestContext = local.get();
//        if(requestContext !=null){
//            Map<String, Object> commonMap = (Map<String, Object>) requestContext.get(ProductApiConstants.RequestContextField.REQCTX_FIELD_REQCTX);
//            if(MapUtils.isNotEmpty(commonMap)){
//                Map<String,Object> institutionRequestParams =  (Map<String, Object>)  commonMap.get(ProductApiConstants.RequestContextField.REQCTX_COMON_INSTREQPMS);
//                if(MapUtils.isNotEmpty(institutionRequestParams)){
//                    reqId = (String)institutionRequestParams.get("reqId");
//                }
//            }
//        }
//        return reqId;
//    }
//
//
//    private static String DEFAULT = "default";
//
//    public static String getInstitutionId() {
//        String institutionId = (String) RequestContext.get(RequestContextField.REQCTX_FIELD_INSTID);
//        return StringUtils.isNotBlank(institutionId) ? institutionId : DEFAULT;
//    }
//
//    public static String getProductId() {
//        String productId = (String) RequestContext.get(RequestContextField.REQCTX_FIELD_PRODUCTID);
//        return StringUtils.isNotBlank(productId) ? productId : DEFAULT;
//    }
//
//    /**
//     * 获取上下文中的原始机构ID
//     * 20211022
//     * @return
//     */
//    public static String getOriginInstitutionId() {
//        String institutionId = (String) RequestContext.get(RequestContextField.REQCTX_FIELD_INSTID_ORIGIN);
//        return StringUtils.isNotBlank(institutionId) ? institutionId : DEFAULT;
//    }
//
//
//    public static String getInstitutionIdFromInstitutionRequestParams() {
//        JSONObject institutionRequestParams = (JSONObject) RequestContext.getSecond(RequestContextField.REQCTX_COMON_INSTREQPMS);
//        String institutionId = institutionRequestParams.getString(ProductApiConstants.CommonRequestParams.COMON_REQ_INSTID);
////        String institutionId = (String) RequestContext.get(RequestContextField.REQCTX_FIELD_INSTID);
//        return StringUtils.isNotBlank(institutionId) ? institutionId : DEFAULT;
//    }

}
